// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
const _ = db.command


// 云函数入口函数
exports.main = async (event, context) => {
    const message = cloud.getWXContext()
    if (event.type == "newAdd") {
        event.newData.post = message.OPENID
        try {
            const chat = await db.collection('chatroom').add({//开房间chatroom
                data: {
                    hold: {
                        name: event.holdName,
                        url: event.holdUrl,
                        id: event.id,
                    },
                    want: {
                        id: message.OPENID,
                        name: event.wantName,
                        url: event.wantUrl
                    },
                    list: [event.newData]
                }
            })

            //添加到俩人的chat_list
            await db.collection('gods').where({
                "_openid": event.id
            }).update({
                data: {
                    "chat_list": _.push(chat._id)
                }
            })

            await db.collection('gods').where({
                "_openid": message.OPENID
            }).update({
                data: {
                    "chat_list": _.push(chat._id)
                }
            })

            return {
                chatroomId: chat._id,
                myId: message.OPENID
            }
        } catch (error) {
            return error;
        }
    } else if (event.type == "add") {
        event.newData.post = message.OPENID
        try {   //找房间
            return await db.collection('chatroom').where({
                "_id": event.roomId
            }).update({   //添加新消息
                data: {
                    "list": _.push(event.newData)
                }
            })
        } catch (error) {
            return error;
        }
    } else if (event.type == "in") {
        //找房间
        const a = await db.collection('chatroom').where({
            "hold.id": event.id,
            "want.id": message.OPENID
        }).get()
        const b = await db.collection('chatroom').where({
            "want.id": event.id,
            "hold.id": message.OPENID
        }).get()
        // 返回房间id
        if (a.data.length) {//我是买家
            return {
                chatroomId: a.data[0]._id,
                myId: message.OPENID
            }
        } else if (b.data.length) {  //我是卖家
            return {
                chatroomId: b.data[0]._id,
                myId: message.OPENID
            }
        } else {
            return "404"
        }
    }

}